package com.dyz.filter;

import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

import java.util.Set;

@Component
public class JwtFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${no.required.urls:/login}")
    private Set<String> noAuthenticationUrls;
    /**
     * 过滤器拦截到请求后该做什么
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断该接口是否需要认证
        //如果不需要认证直接放行
        if(!NeedAuthentication(exchange)){
            return chain.filter(exchange);
        }
        //取出请求头中的token
      String token= getUserToken(exchange);
        if(StringUtils.isEmpty(token)){
            return bulideNoAuthorization(exchange);
        }
        Boolean hasKey = stringRedisTemplate.hasKey(token);

        if(hasKey!=null&&hasKey){
            //token有效放行
            return chain.filter(exchange);
        }
        return bulideNoAuthorization(exchange);
        //判断token是否正确
    }

    /**
     * 给用户一个错误的响应
     * @param exchange
     * @return
     */
    private Mono<Void> bulideNoAuthorization(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("code",401);
      jsonObject.put("msg","NoAuthorization");
      return response.writeWith(Mono.just(response.bufferFactory().wrap(jsonObject.toJSONString().getBytes())));
    }

    /**
     * 获取请求头中的token
     * @param exchange
     * @return
     */
    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        return token==null?null:token.replace("bearer ","");
    }

    /**
     *  判断该接口是否需要认证
     * @param exchange
     * @return
     */
    private boolean NeedAuthentication(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if(noAuthenticationUrls.contains(path)){
            return false;
        }
        return true;
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
